extends Area2D

@export var monster_name : String = "鸡"  # 怪物名
@export var monster_lever : int = 1  # 怪物等级
@export var monster_HP : float = 46  # 怪物血量
@export var monster_currentHP : float = 46
@export var monster_dam : float = 1  # 怪物攻击
@export var monster_def : float = 0  # 怪物防御
@export var exp_value : int = 28  # 怪物提供的经验值

@onready var monster_name_label: Label = $MonsterBG/MonsterName  # 名字文本框
@onready var lv_label: Label = $MonsterBG/LVBG/LVLabel           # 等级文本框
@onready var hp_label: Label = $MonsterBG/HPBar/HPLabel          # 血量文本框
@onready var hp_bar: TextureProgressBar = $MonsterBG/HPBar       # 血量条

var horizontal_move_distance: float = 120.0  # 左右移动距离
var vertical_move_distance: float = 130.0    # 上下移动距离
var move_duration: float = 0.5               # 移动持续时间(单位：秒)
var attack_distance: float = 5.0            # 攻击位移距离(单位：像素)
var attack_duration: float = 0.1             # 单次攻击动画时间(来回共0.2秒)
var player: CharacterBody2D = null           # 玩家
var is_moving : bool = false                 # 移动状态
var is_attacking: bool = false               # 攻击状态
var timer: Timer                             # 计时器
var original_position: Vector2               # 记录原始位置用于攻击后复位
# 添加移动范围限制的边界
var move_area_min := Vector2(4, 56)    # 左上角最小边界
var move_area_max := Vector2(604, 576) # 右下角最大边界

@onready var raycasts = {
	"up" : $RayCastUp,
	"down" : $RayCastDown,
	"left": $RayCastLeft,
	"right": $RayCastRight,
	"up_left": $RayCastUpLeft,
	"up_right": $RayCastUpRight,
	"down_left": $RayCastDownLeft,
	"down_right": $RayCastDownRight
}

func _ready() -> void:
	update_Data()
	
	# 纪录当前位置
	original_position = position
	
	# 初始化计时器
	timer = Timer.new()
	add_child(timer)
	timer.wait_time = 1  # 行动间隔时间
	timer.timeout.connect(_on_timer_timeout)
	timer.start()
	
	# 安全地查找玩家
	_find_player()

# 添加一个新方法来安全地查找玩家
func _find_player():
	var players = get_tree().get_nodes_in_group("player")
	if players.size() > 0:
		player = players[0]
	else:
		player = null

func _on_timer_timeout() -> void:
	if is_moving or is_attacking:
		return  # 如果正在移动或攻击，跳过这次检测
	
	# 确保玩家引用有效
	if not is_instance_valid(player):
		_find_player()
		if not player:
			return  # 如果仍然找不到玩家，跳过
	
	if _check_player_detection():  # 先检查射线是否碰到玩家
		_attack_player()
	elif player:  # 只有没检测到玩家且玩家存在时才移动
		var direction = _get_best_direction()  # 决定移动方向（只允许上下左右）
		_move_towards_direction(direction)

# 计算移动方向
func _get_best_direction() -> Vector2:
	if not player:
		return Vector2.ZERO
	
	var player_dir = (player.global_position - global_position).normalized()
	
	# 只考虑上下左右四个方向
	var possible_directions = [
		Vector2.UP,
		Vector2.DOWN,
		Vector2.LEFT,
		Vector2.RIGHT
	]
	
	# 检查每个方向是否有障碍物
	var valid_directions = []
	for dir in possible_directions:
		if not _is_direction_blocked(dir):
			valid_directions.append(dir)
	
	# 如果没有有效方向，返回零向量
	if valid_directions.size() == 0:
		return Vector2.ZERO
	
	# 选择最接近玩家方向的
	var best_dir = valid_directions[0]
	var best_dot = player_dir.dot(best_dir)
	
	for dir in valid_directions.slice(1):
		var dot = player_dir.dot(dir)
		if dot > best_dot:
			best_dot = dot
			best_dir = dir
	
	return best_dir

# 检查指定方向是否有障碍物（包括其他怪物）
func _is_direction_blocked(direction: Vector2) -> bool:
	# 根据方向选择对应的 RayCast2D
	var raycast = null
	if direction == Vector2.UP:
		raycast = $RayCastUp
	elif direction == Vector2.DOWN:
		raycast = $RayCastDown
	elif direction == Vector2.LEFT:
		raycast = $RayCastLeft
	elif direction == Vector2.RIGHT:
		raycast = $RayCastRight
	
	if raycast:
		raycast.force_raycast_update()
		if raycast.is_colliding():
			var collider = raycast.get_collider()
			# 检查是否是其他Area2D或障碍物，包括其他怪物
			if collider is Area2D or collider is StaticBody2D:
				if collider != self and collider != player:  # 排除自己和玩家
					# 如果是怪物，检查它是否处于攻击状态
					if collider.has_method("is_attacking") and collider.is_attacking:
						return false  # 忽略正在攻击的怪物
					return true
	
	# 添加额外的空间查询检测，防止怪物重叠
	var space_state = get_world_2d().direct_space_state
	var query = PhysicsShapeQueryParameters2D.new()
	query.collision_mask = collision_mask
	query.collide_with_areas = true
	query.collide_with_bodies = true
	
	# 创建移动方向的形状查询
	var shape = $CollisionShape2D.shape
	var move_dist = vertical_move_distance if direction.y != 0 else horizontal_move_distance
	var target_position = global_position + direction * move_dist
	
	query.transform = Transform2D(0, target_position)
	query.shape_rid = shape.get_rid()
	
	var results = space_state.intersect_shape(query)
	
	# 检查查询结果中是否有其他怪物或障碍物
	for result in results:
		var obj = result.collider
		if obj != self and obj != player:  # 排除自己和玩家
			# 如果是怪物，检查它是否处于攻击状态
			if obj.has_method("is_attacking") and obj.is_attacking:
				continue  # 忽略正在攻击的怪物
			return true
	
	return false

# 开始移动前再次确认方向是否安全
func _move_towards_direction(direction: Vector2):
	if direction == Vector2.ZERO or is_moving or is_attacking:
		return
	
	# 再次确认方向是否被阻挡
	if _is_direction_blocked(direction):
		return
	
	is_moving = true
	# 根据方向决定移动距离
	var move_dist = vertical_move_distance if direction.y != 0 else horizontal_move_distance
	var target_position = global_position + direction * move_dist
	
	# 添加边界检查，确保不会超出限定范围
	target_position.x = clamp(target_position.x, move_area_min.x, move_area_max.x)
	target_position.y = clamp(target_position.y, move_area_min.y, move_area_max.y)
	
	# 如果移动后位置和当前位置相同，则不移动
	if target_position == global_position:
		is_moving = false
		return
	
	# 使用 Tween 平滑移动
	var tween = create_tween()
	tween.tween_property(self, "global_position", target_position, move_duration)
	tween.tween_callback(_on_move_completed)
	
	# 移动过程中暂时禁用碰撞
	$CollisionShape2D.set_deferred("disabled", true)
	await get_tree().create_timer(move_duration).timeout
	$CollisionShape2D.set_deferred("disabled", false)

func _on_move_completed():
	is_moving = false

func _check_player_detection() -> bool:
	# 确保玩家有效
	if not is_instance_valid(player):
		return false
	
	# 检查所有射线是否碰到玩家
	for ray in raycasts.values():
		if ray.is_colliding() and ray.get_collider() == player:
			return true
	return false

func _attack_player():
	if is_attacking or is_moving or not is_instance_valid(player):
		return
	
	is_attacking = true
	original_position = position  # 记录攻击前位置
	
	# 计算玩家方向
	var attack_direction = (player.global_position - global_position).normalized()
	var attack_target = position + attack_direction * attack_distance
	
	# 创建攻击动画Tween
	var attack_tween = create_tween()
	attack_tween.set_trans(Tween.TRANS_BACK)  # 添加弹性效果
	
	# 向前攻击
	attack_tween.tween_property(self, "position", attack_target, attack_duration)
	# 返回原位
	attack_tween.tween_property(self, "position", original_position, attack_duration)
	
	# 动画完成后执行实际攻击逻辑
	attack_tween.tween_callback(_on_attack_completed)

func _on_attack_completed():
	is_attacking = false
	if player and is_instance_valid(player):
		player.take_damage(monster_dam)

func take_damage(damage: float):
	monster_currentHP -= damage
	update_Data()
	_play_hurt_effect()
	if monster_currentHP <= 0:
		# 死亡时通知玩家获得经验值
		if player and is_instance_valid(player):
			player.gain_exp(exp_value)
		queue_free()

func _play_hurt_effect():
	# 简单的受伤闪烁效果
	var tween = create_tween()
	tween.tween_property(self, "modulate", Color.RED, 0.1)
	tween.tween_property(self, "modulate", Color.WHITE, 0.1)

func update_Data():
	# 初始化怪物数据
	monster_name_label.text = monster_name
	lv_label.text = str(monster_lever)
	hp_label.text = str(int(monster_currentHP)) + " / " + str(int(monster_HP))
	hp_bar.value = monster_currentHP / monster_HP * 100
